package com.ruoyi.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.spring.SpringUtils;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by qhong on 2018/7/3 16:55
 **/
public class OkHttpUtil{

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);

    /**
     * 根据map获取get请求参数
     * @param queries
     * @return
     */
    public static StringBuffer getQueryString(String url,Map<String,String> queries){
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        return sb;
    }

    /**
     * 调用okhttp的newCall方法
     * @param request
     * @return
     */
    private static String execNewCall(Request request){
        Response response = null;
        try {
//            OkHttpClient okHttpClient = SpringUtils.getBean(OkHttpClient.class);
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .followRedirects(true)  //禁制OkHttp的重定向操作，我们自己处理重定向
                    .followSslRedirects(false)
                    .build();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * get
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String get(String url, Map<String, String> queries) {
        StringBuffer sb = getQueryString(url,queries);
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        return execNewCall(request);
    }

    public static String get(String url)throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
                .followRedirects(true)
                .build();
        System.out.println(url);
        Request request = new Request.Builder().url(url).get().build();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(response.code());
        String json = response.body().string();
        System.out.println(json);
        return json;
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String postFormParams(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        return execNewCall(request);
    }


    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public static String postJsonParams(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return execNewCall(request);
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public static String postXmlParams(String url, String xml) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return execNewCall(request);
    }

    final OkHttpClient client = new OkHttpClient().newBuilder()
            .followRedirects(false)
            .followSslRedirects(false)
            .cookieJar(new LocalCookieJar())
            .build();

    //CookieJar是用于保存Cookie的
    class LocalCookieJar implements CookieJar {
        List<Cookie> cookies;
        @Override
        public List<Cookie> loadForRequest(HttpUrl arg0) {
            if (cookies != null)
                return cookies;
            return new ArrayList<Cookie>();
        }

        @Override
        public void saveFromResponse(HttpUrl arg0, List<Cookie> cookies) {
            this.cookies = cookies;
        }

    }

    public void sendGet(){
        //构造一个POST请求
        RequestBody body = new FormBody.Builder().build();

        Request request = new Request.Builder().url("http://222.195.8.201/pass.asp").post(body).build();
        client.newCall(request).enqueue(new Callback() {
            String json = null;
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                /**
                 * 如果不用CookieJar,那么就要自己去解析返回的Set-Cookie字段,解析之后通过addHeader("Cookie", cookie)
                 * 添加Cookie请求头
                 */
//              List<String> cookies =  response.headers("Set-Cookie");
//              String cookie = "";
//              for(int i=cookies.size()-1; i>=0; i--){
//                  cookie = cookie+ cookies.get(i).replace("path=/", "") + " ";
//              }

                //做GET请求
                Request redirectRequest = new Request.Builder().url("http://222.195.8.201/student/asp/Select_Success.asp")
//                    .addHeader("Cookie", cookie)
                        .build();
                //拿到登录后操作的某个网页的内容
                Response response2 = client.newCall(redirectRequest).execute();
                String result = response2.body().string();
                System.out.println(result);
                json = result;
            }

            @Override
            public void onFailure(Call arg0, IOException arg1) {

            }
        });

    }

    OkHttpClient client1 = new OkHttpClient.Builder().followRedirects(false).addInterceptor(new RedirectInterceptor()).build();

    //处理重定向的拦截器
    public class RedirectInterceptor implements Interceptor {


        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            int code = response.code();
            if (code == 307) {
                //获取重定向的地址
                String location = response.headers().get("Location");
                //重新构建请求
                Request newRequest = request.newBuilder().url(location).build();
                response = chain.proceed(newRequest);
            }
            return response;
        }
    }




}